﻿using System.Data;
using System.Data.SqlClient;
using System.Linq;

namespace Adams.Web.Data.TarawehPrayers
{
    public static class Index
    {
        public static Adams.Web.Models.TarawehPrayers.Index.PageLoad PageLoad()
        {
            var data = new Adams.Web.Models.TarawehPrayers.Index.PageLoad() { 
                Locations = new Shared.Entities.TarawehPrayers.LocationCollection()
            };

            using (SqlDataReader dr = DB.RunDataReader(@"
SELECT LocationID, Name, Street, Street2, City, State, ZipCode, Latitude, Longitude, DisplayOrder
FROM TarawehPrayers.Locations
ORDER BY DisplayOrder

SELECT *
FROM TarawehPrayers.Prayers
ORDER BY DisplayOrder
", CommandType.Text))
            {

                while (dr.Read())
                {
                    var location = DB.InitFromReader<Shared.Entities.TarawehPrayers.Location>(dr, new ColMap{ NameInDb="LocationID", NameInObject="ID" });
                    location.Prayers = new Shared.Entities.TarawehPrayers.PrayerCollection();
                    data.Locations.Add(location);
                }

                dr.NextResult();

                while (dr.Read())
                {
                    var prayer = DB.InitFromReader<Shared.Entities.TarawehPrayers.Prayer>(dr, new ColMap{ NameInDb="PrayerID", NameInObject="ID" });
                    data.Locations.Where(l => l.ID == dr["LocationID"].DbInt()).FirstOrDefault().Prayers.Add(prayer);
                }

                return data;
            }
        }
    }
}
